package com.soul.parse;

import com.soul.annotation.*;
import com.soul.enums.RequestProtocol;
import com.soul.net.http.HttpRequest;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.HashMap;

/**
 * 请求处理
 */
public class ParseRequest {
    
    public HttpRequest parse(Method method,Object[] args){
        if (method.isAnnotationPresent(HTTPRequest.class)){
            HTTPRequest annotation = method.getAnnotation(HTTPRequest.class);
            if (annotation != null){
                HttpRequest request = new HttpRequest(annotation.url());
                setProtocol(request,annotation.enableHttps());
                timeout(request);
                request.setEncoding("utf-8");
                request.setMethod(annotation.method());
                processArgs(method,request,args);
                processUrl(request);
                return request;
            }
        }
        return null;
    }

    private void processUrl(HttpRequest request) {
        String url = request.getUrl();
        ReplaceTag replaceTag = new ReplaceTag("{","}",
                (startTag, content, endTag) -> request.getPathParams().get(content));
        String replace = replaceTag.replace(url);
        request.setUrl(replace);
    }

    private void processArgs(Method method, HttpRequest request,Object[] args) {
        Parameter[] parameters = method.getParameters();
        if (parameters != null && parameters.length > 0){
            for (int i = 0; i < parameters.length; i++) {
                Parameter parameter = parameters[i];
                PathVar pathVar = parameter.getAnnotation(PathVar.class);
                if (pathVar != null){
                    if (request.getPathParams() == null) {
                        request.setPathParams(new HashMap<>());
                    }
                    request.putPathParams(pathVar.value(),args[i].toString());
                    continue;
                }
                ParamVar paramVar = parameter.getAnnotation(ParamVar.class);
                if (paramVar != null){
                    if (request.getQueryParams() == null){
                        request.setQueryParams(new HashMap<>());
                    }
                    request.putQueryParams(paramVar.value(),args[i].toString());
                }
            }
        }
    }

    private void timeout(HttpRequest request) {
        request.setConnectTimeout(3000);
        request.setReadTimeout(5000);
    }

    private void setProtocol(HttpRequest request,boolean enableHttps){
        if (enableHttps) {
            request.setProtocol(RequestProtocol.HTTPS);
        }else{
            request.setProtocol(RequestProtocol.HTTP);
        }
    } 
}
